// 后台首页数据

package basic

import (
	"api/common/logger"
	"api/common/orm"
	"api/common/web"
	"fmt"
	"net/http"
	"time"
)

// @TagName 后台首页数据
// @Controller HomeController
type HomeController struct{}

// @Title 后台首页数据
// @Param {"year":23}
// @Route /home/data --> Data
// @Method post
func (this *HomeController) Data(w http.ResponseWriter, r *http.Request) {
	defer web.PanicHandler(w, r)
	inputJson, msg := web.TokenCheckRequest(r)
	if msg != nil {
		web.ServeJSON(w, msg)
		return
	}

	year := inputJson["year"]
	var yy uint32
	if year != nil {
		y2 := uint32(year.(float64))
		if y2 != uint32(time.Now().Year()) {
			// 忽略今年
			yy = y2
		}
	}

	// 获取学生总数
	infoTable := "student_info"
	recordTable := "student_operate_record"
	if yy > 0 {
		infoTable += "_%d"
		infoTable = fmt.Sprintf(infoTable, yy)
		recordTable += "_%d"
		recordTable = fmt.Sprintf(recordTable, yy)
	}
	sql := "select" +
		" (select count(1) from %s where `exit`=false and `status`>=1) status1," +
		" (select count(1) from %s where `exit`=false and `status`=2 or `status`=5) status2," +
		" (select count(1) from %s where `exit`=false and `status`=5) status3"
	sql = fmt.Sprintf(sql, infoTable, infoTable, infoTable)
	countStatus1 := 0
	countStatus2 := 0
	countStatus3 := 0
	conn := orm.NewOrm()
	err := conn.Raw(sql).QueryRow(&countStatus1, &countStatus2, &countStatus3)
	if err != nil {
		logger.Error("获取学生总数发生错误", err)
		web.ServeJSON(w, web.JsonMsg{false, "获取学生总数发生错误" + err.Error(), 1})
		return
	}
	data := map[string]interface{}{}
	data["countStatus1"] = countStatus1
	data["countStatus2"] = countStatus2
	data["countStatus3"] = countStatus3

	// 获取最新动态
	data2 := []map[string]interface{}{}
	sql = "select i.`name`, i.nick_name, i.weixin_id, i.phone, r.`status`, r.remark, r.add_time" +
		" from %s i left join %s r on r.student_id=i.id" +
		" order by r.add_time desc limit 50"
	sql = fmt.Sprintf(sql, infoTable, recordTable)
	data2, err = conn.Raw(sql).QueryMaps()
	if err != nil {
		logger.Error("获取最新动态发生错误", err)
		web.ServeJSON(w, web.JsonMsg{false, "获取最新动态发生错误" + err.Error(), 1})
		return
	}
	data["latestData"] = data2

	// 获取专业报名情况
	data3 := []map[string]interface{}{}
	sql = "select s.id, s.`name`," +
		" (select count(1) from %s i where i.`exit`=false and (i.`status`=2 or i.`status`=5) and i.special_id=s.id and i.sex=false) num0," +
		" (select count(1) from %s i where i.`exit`=false and (i.`status`=2 or i.`status`=5) and i.special_id=s.id and i.sex=true ) num1" +
		" from basic_special s where s.pid>0 order by num0+num1 desc limit 10"
	sql = fmt.Sprintf(sql, infoTable, infoTable)
	data3, err = conn.Raw(sql).QueryMaps()
	if err != nil {
		logger.Error("获取专业报名情况发生错误", err)
		web.ServeJSON(w, web.JsonMsg{false, "获取专业报名情况发生错误：" + err.Error(), 1})
		return
	}
	data["specialData"] = data3

	// 获取专业报名名额
	data5 := []map[string]interface{}{}
	sql = "select id, `name`, quota," +
		" (select count(1) from student_info where `exit` = false" +
		" and special_id=s.id and (`status`=1 or `status`=2 or `status`=5)) quota2" +
		" from basic_special s where pid > 0"
	data5, err = conn.Raw(sql).QueryMaps()
	if err != nil {
		logger.Error("获取专业报名名额发生错误", err)
		web.ServeJSON(w, web.JsonMsg{false, "获取专业报名名额发生错误：" + err.Error(), 1})
		return
	}
	data["quotaData"] = data5

	// 获取每日报名趋势
	now := time.Now()
	d, _ := time.ParseDuration("-24h")
	data4 := []map[string]interface{}{}
	sql = "select"
	for i := 0; i < 10; i += 1 {
		if i > 0 {
			now = now.Add(d)
		}
		ts := now.Unix()
		tm := time.Unix(ts, 0)
		str := tm.Format("2006-01-02")
		sql += " (select count(1) from " + recordTable + " where `status`=1 and" +
			" add_time>='" + str + " 00:00:00' and add_time<='" + str + " 23:59:59') '" + str + "'"
		if i < 9 {
			sql += ","
		}
	}
	data4, err = conn.Raw(sql).QueryMaps()
	if err != nil {
		logger.Error("获取每日报名趋势发生错误", err)
		web.ServeJSON(w, web.JsonMsg{false, "获取每日报名趋势发生错误" + err.Error(), 1})
		return
	}
	data["trendData"] = data4

	// 获取住校男生、住校女生、跑堂男生、跑堂女生的人数
	type Counts struct {
		Lodging1sex1 uint32 `json:"lodging1sex1"`
		Lodging1sex0 uint32 `json:"lodging1sex0"`
		Lodging0sex1 uint32 `json:"lodging0sex1"`
		Lodging0sex0 uint32 `json:"lodging0sex0"`
	}
	counts := &Counts{}
	where := "`exit`=false and `status`>=2"
	sql = "select" +
		" (select count(1) from %s where " + where + " and lodging=true  and sex=true)  lodging1sex1," +
		" (select count(1) from %s where " + where + " and lodging=true  and sex=false) lodging1sex0," +
		" (select count(1) from %s where " + where + " and lodging=false and sex=true)  lodging0sex1," +
		" (select count(1) from %s where " + where + " and lodging=false and sex=false) lodging0sex0"
	sql = fmt.Sprintf(sql, infoTable, infoTable, infoTable, infoTable)
	err = conn.Raw(sql).QueryRow(counts)
	if err != nil {
		logger.Error("获取学生人数发生错误", err)
		web.ServeJSON(w, web.JsonMsg{false, "获取学生人数发生错误" + err.Error(), 1})
		return
	}
	data["counts"] = counts

	result := map[string]interface{}{}
	result["status"] = 0
	result["success"] = true
	result["msg"] = "查询成功"
	result["data"] = data
	web.ServeJSON(w, result)
}
